package com.netty.nettyserver.handler;

import com.netty.nettyserver.disrapter.RequestDispatcher;
import com.netty.nettyserver.others.MethodInvokeMeta;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author shengtao
 * @Description: 请求处理类
 * @date 2018/09/20 13:36
 */
@Component
@ChannelHandler.Sharable
@Slf4j
public class ServerChannelHandlerAdapter extends ChannelHandlerAdapter {

    /**
     * 请求分发器
     */
    @Autowired
    private RequestDispatcher dispatcher;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MethodInvokeMeta invokeMeta = (MethodInvokeMeta)msg;
        if(invokeMeta.getMethodName().endsWith("toString()")
                && !"class java.lang.String".equals(invokeMeta.getReturnType().toString())){
            log.info("客户端传入参数 :{},返回值：{}",invokeMeta.getArgs(), invokeMeta.getReturnType());
        }else {
            //转发
            dispatcher.dispatcher(ctx,invokeMeta);
        }
    }
}
